<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\exception\ValidateException;
use think\Request;

class Book extends Base
{
    /**
     * index #书籍列表
     * api post /{controller}/{method}
     * @param int id ID
     * @param string b_title 名称
     * @param string b_author 作者
     * @param string b_isbn ISBN
     * @return int code 状态码
     * @return string msg 消息
     * @return array data 数据
     *
     * @auth kouweihong
     * @date 2020/11/24
     */
    public function index()
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 15);
        $field = input('field');
        $value = input('value');

        $where = [];
        $field && $value && $where[$field] = $value;
        $list = \app\common\model\Book::where($where)->paginate($pageSize);
        $this->success($list);
    }

    /**
     * add #添加书籍
     * api post /{controller}/{method}
     *
     * @auth kouweihong
     * @date 2020/11/24
     */
    public function add()
    {
        $this->request->isPost() || $this->error('非法操作');
        $params = input('post.');
        $params || $this->error('提交参数为空');

        try {
            $params['user_type'] = $this->auth->user_type;
            $params['user_id'] = $this->auth->id;
            validate(\app\common\validate\Book::class)->check($params);

            //保存数据
            $res = (new \app\common\model\Book())->save($params);
            $res === false && $this->error('操作失败');

            $this->success();
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * findBook #查找书籍
     * api post /{controller}/{method}
     *
     * @auth kouweihong
     * @date 2020/11/25
     */
    public function findBook()
    {
        //获取参数
        $id = input('id');
        $bTitle = input('b_title');
        (!$id && !$bTitle) && $this->error('参数错误');

        //查找
        $where = [];
        $id && $where['id'] = $id;
        $bTitle && $where['b_title'] = $bTitle;
        $book = \app\common\model\Book::where($where)->find();
        $book || $this->error('书籍信息不存在');

        $this->success($book);
    }

    /**
     * del #删除书籍
     * api post /{controller}/{method}
     *
     * @auth kouweihong
     * @date 2020/12/4
     */
    public function del($id)
    {
        $id || $id = input('id');
        $id || $this->error('参数错误');

        //查询
        $book = \app\common\model\Book::find($id);
        $book || $this->error('信息记录不存在');
        $book->status == \app\common\model\Book::STATUS_F_1 && error_log('此书籍已删除');

        //保存
        $res = $book->save(['status' => \app\common\model\Book::STATUS_F_1]);
        $res === false && $this->error('操作失败');

        $this->success();
    }
}
